var liveIM = require('../../utils/live-im') ;
var TIM = require('../../miniprogram_npm/tim-wx-sdk/index');
// var COS = require('../../miniprogram_npm/cos-wx-sdk-v5/index');
var WxParse = require('../../../wxParse/wxParse');
var SVGA = require("../../utils/svga.min");

var app = getApp();
var timer=null,timer2=null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuButton:{}, //胶囊位置
    systemInfo:{}, //系统信息
    title:{}, //logo
    customerId:false, //获取手机号
    smallWindow:['push'], // 小窗口

    kefu:{yes:false, img:'', name:''}, // 是否客服
    liveData:{ //直播间数据
      connect_pull_url:'', //连麦
      connect_status:'0'
    },
    liveStart:false, //直播间状态
    newLiveUrl:'', //直播地址
    liveType:0,  //直播类型，0=直播模式，1=视频预告模式
    lookCount:0, //观看量
    subscribe:0, //是否订阅
    tplID:null, //订阅消息id

    tabActive:0, // 导航栏
    tabViewHeight:200, // 功能区高度

    txtMsgList:[], //聊天室内容
    txtMsg:'', //聊天
    keyHeight:0, //键盘高度
    giftList:[], //礼物列表
    showGift:false, //礼物列表
    giftItem:{}, //选中礼物
    showCount:false, //礼物数量
    giftCountList:[1314,520,100,88,66,10,1], //礼物数量
    giftCount:1, //礼物数量
    giftSubmitStyle:'',
    gift:true, //礼物效果
    giftPoints:0, //积分
    giftTipList:[], //奖品提示列表
    giftTipList1:[], //奖品提示列表
    parserEnd:true,

    zanStart:0, //点赞动作
    zanCount:0, //点赞数量
    showZan:false, //点赞效果

    goodsList:[], //商品列表
    cradList:[], //卡券列表
    shareList:[], //达人帮列表

    showLottery:false, //抽奖弹框
    lotteryList:[], // 抽奖列表
    lotteryItem:{}, // 当前抽奖
    lotteryStatus:0, // 抽奖状态
    uuidYes:'', // 当前自己中奖口令
    uuidCoupon:'', // 当前自己中奖优惠券
    lotteryHistory:[], // 中奖列表
    showLotteryHistory:false, //中将列表

    showModal:false, // 投诉弹窗

    showGoodsTip:false, //推送商品弹窗
    showContrastTip:false, //推送对比图弹窗
    showCradTip:false, //推送优惠券弹窗
    tipIdx:-1, //推送商品,优惠券
    showContrast:false, //对比图+商品弹窗

    goodsCountTipList:[],
    goodsMoneyTipList:[], //购买提示
    noMsg:[], // 禁言

    HB:{ // 红包
      id:'0', show:false,time:10
    },
    showQA:'',
    listQA:[],
    indexQA:0,
    timeQA:10,
    timeOutQA:null,
    rewardQA:false, //是否答题结束
    getQA:false, //是否有奖励
    replyName:'',  // LCL 回复昵称
    sign_status:0,  // LCL 签到状态
    enter_mode:1,   //LCL 直播间模式：1.所有都可进入，2.付费模式，3.邀请码模式，4.白名单模式
    live_goods_id:0,  //LCL 付费模式商品ID
    live_goods_price:0,  //LCL 付费模式价格
    txtPwds:'',  //LCL 邀请码模式：密码
    enter_msg:'',  //LCL 特定直播间描述
    substatus:1,   //LCL 订阅通知显示
    notRefresh: false, // 不允许刷新
    linkman: '', // 自提联系人
    phone: '', // 自提联系电话
    disabled: false,   // 禁用submit按钮
    showCheckin:false,   // 签到弹出
    showRule:false,   // 签到规则弹出
    checkin_my_status:0,   // 自己签到的状态
    checkin_share_status:0,   // 朋友签到的是否可领奖状态  不用了，后台返回
    signup_mode:1,   //签到模式，1：正常模式，2：奖励模式
    signData:{},    //签到信息
    shareData:[],   //签到好友列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    let t = this,token = wx.getStorageSync('ACCESS_TOKEN'),scene = app.getSceneData(e);
    e.id = e.id ? e.id : scene.id;
    wx.setKeepScreenOn({keepScreenOn: true});
    if(token){
      t.init(t,e,token);
    }else {
      app.args.page.onLoad(this, e)
    }
  },
  init(t,e,token){
    let d=t.data,
      menuButton=wx.getMenuButtonBoundingClientRect(),
      systemInfo=wx.getSystemInfoSync();
    let tabViewHeight = 120 + menuButton.top + systemInfo.windowWidth*0.55;
    t.setData({
      menuButton,
      systemInfo,
      c_app:app,
      token:token,
      parmas:e,
      options:e,
      _api_live: app.args.api.siteinfo.sitelive,
      userInfo:wx.getStorageSync('USER_INFO'),
      tabViewHeight:Math.floor(tabViewHeight)
    },function () {
      t.data.kefu={yes:false, name:t.data.userInfo.nickName, img:t.data.userInfo.avatarUrl}
      t.getLiveCheck(t,e,token);
      //t.getLiveData(t,e,token);
      //t.getGoodsList();
      //t.getCradList();
      //t.getShareList();
    })
  },

  //获取直播间验证信息
  getLiveCheck(t,e,token){
    var d = t.data;
    app.args.request({
      url: d._api_live + 'live/checkRoomEnter',
      data:{
        hosId: app.args.api.siteinfo.hosId2,
        openId:token,
        liveId:e.id
      },
      success(res){
        //console.log(res)
        if (res.need_phone == 1) {
          wx.navigateTo({
            url: '/pages/phone/index',
          })
        } 
        if(res.is_ok == 1){
          t.setData({
            enter_mode:1,
            substatus:1,
            showInput:true,
            sign_status:0,
            live_goods_price:0,
            live_goods_id:0,
          })
          t.getLiveData(t,e,token);
          t.getCradList();
          t.getGoodsList();
          t.getShareList();
        }else{
          t.setData({
            liveData:res,
            'liveData.innerbgimg':res.background_img,
            lookCount:res.look_num || 0,
            enter_msg:res.enter_msg,
            live_goods_price:res.goods_price,
            live_goods_id:res.enter_goods_id,
            substatus:0,
            enter_mode:res.enter_mode,
            showInput:false,
            sign_status:1,
          })
        }
      }
    })
  },
  getLiveData(t,e,token){
    var d = t.data;
    app.args.request({
      url: d._api_live + 'live/getRoomInfo',
      data:{
        hosId: app.args.api.siteinfo.hosId2,
        userId:token,
        liveId:e.id,
        oriToken:e.oriToken || ''
      },
      success(res){
        //console.log(res)
        // live_status 1:直播中，2：已结束，3：未开始
        if(res.result == 0) {
          if(res.staffList.length){
            res.staffList.forEach(item=>{
              if(item.access_token == token){
                t.data.kefu={yes:true, name:item.nickname, img:app.args.api.siteinfo.logo}
              }
            })
          }
          // 加载历史消息
          if(res.history_msg.length){
            d.txtMsgList = res.history_msg
          }
          d.txtMsgList.push({
            img:app.args.api.siteinfo.logo, name:'欢迎', token:'',
            txt: d.userInfo.nickName + ' 进入直播间',
            yes:false,admin:false
          })
          t.setData({
            liveData:res,
            liveStart:res.live_status == 1?true:false,
            lookCount:res.look_num || 0,
            zanCount:res.zan_num || 0,
            txtMsgList:d.txtMsgList,
            kefu:d.kefu,
            subscribe:res.subscribe,
            tplID:res.tplID,
            newLiveUrl:res.pull_url,
            liveType:res.liveType,
            signup_mode:res.signup_mode
          },function () {
            t.setInitIM(t,token,res);
            t.setLotteryList(res.lotteryData);
            t.setWxParse(res.liver_content);
          })
          // 加载历史消息-滚动到最底下
          if(res.history_msg.length){
            wx.pageScrollTo({selector:'#footer'});
          }
        }
      }
    })
  },

  // IM
  setInitIM(t,token,roomInfo){
    const configIM = {
      options:{SDKAppID:app.args.api.siteinfo.SDKAppID},
      setLogLevel:1,
      user:{
        userID: token,
        userSig: roomInfo.usersig
      },
      //群
      group:{ groupID: roomInfo.im_group_id, type: TIM.TYPES.GRP_AVCHATROOM },
      // 接受所有群消息
      message_received:t.getImMsg,
      error(e){
        //console.log('error-1',e)
      }
    }
    liveIM.init(configIM,TIM,'',t);
  },
  getImMsg(e){
    //console.log(e)
    let t = this;
    e.data.forEach(item=>{
      switch(item.type) {
        case 'TIMTextElem':
          t.getTextMsg(t,item.payload.text)
          break;
        case "TIMCustomElem":
          t.getCustomMsg(item,t)
          break;
        default:
          //console.log('未定义类型',item)
      }
    })
  },

  getCustomMsg(e,t){
    switch(e.payload.data) {
      case 'pushZan':
        //console.log('点赞量',e.payload.extension)
        t.setData({zanCount:t.data.zanCount+(e.payload.extension-0)})
        break;
      case "pushLook":
        //console.log('观看量',e.payload.extension)
        t.setData({lookCount:t.data.lookCount+(e.payload.extension-0)})
        break;
      case "pullPlay":
        //console.log('开播');
        t.setData({liveStart:true})
        break;
      case "pushMoney":
        //console.log('购买',e.payload.extension);
        t.setMoneyTip(e.payload.extension)
        break;
      case "pushWXGoodsTips":
        //console.log('商品剩余');
        t.setGoodsCountTip(e.payload.extension)
        break;
      case "updateGoods":
        //console.log('更新商品');
        t.getGoodsList()
        break;
      case "updateCrad":
        //console.log('更新卡券');
        t.getCradList()
        break;
      case "beginLottery":
        //console.log('开始抽奖',e.payload.extension);
        t.startLottery(e.payload.extension)
        break;
      case "pullLottery":
        //console.log('已开奖',e.payload.extension);
        t.endLotter(e.payload.extension)
        break;
      case "pullGoods":
        //console.log('商品推送',e.payload.extension);
        let ex = JSON.parse(e.payload.extension);
        t.setGoodsTip(ex.goodsId,t);
        break;
      case "pullGoodsImg":
        //console.log('对比图',e.payload.extension);
        t.setContrastTip(t,e.payload.extension)
        break;
      case "pullCoupon":
        //console.log('优惠券',e.payload.extension);
        var data = JSON.parse(e.payload.extension)
        t.setCradTip(t,data.couponId)
        break;
      case "pullUrl":
        //console.log('切换镜头',e.payload.extension);
        let ext = JSON.parse(e.payload.extension)
        //console.log(ext);
        t.setData({
          newLiveUrl:ext.url,
          liveType:ext.type,
          liveStart:true
        })
        break;
      case "pushChatMsg":
        //console.log('自定义聊天',e.payload.extension);
        t.getTextMsg(t,e.payload.extension);
        break;
      case "pushGift":
        //console.log('礼物',e.payload.extension);
        t.setGiftTip(JSON.parse(e.payload.extension))
        break;
      case "pullHB":
        //console.log('红包',e.payload.extension);
        t.setHB(JSON.parse(e.payload.extension))
        break;
      case "pushWXQA":
        //console.log('问答',e.payload.extension);
        t.setQATime(JSON.parse(e.payload.extension))
        break;
      case "pushgoodIdWant":
        //console.log('想要',e.payload.extension);
        t.setWant(JSON.parse(e.payload.extension))
        break;
      case "pushConnectUrl":
        //console.log('连麦',e.payload.extension);
        let o = JSON.parse(e.payload.extension);
        t.setData({
          'liveData.connect_status':o.status,
          'liveData.connect_pull_url':o.connect_url
        })
        break;
      default:
        //console.log('未定义类型2',e)
    }
  },
  // 聊天室
  getTextMsg(t,e){
    var txt = JSON.parse(e);
    var txtMsgList = t.data.txtMsgList;
    if(txt.type){
      txt.admin=true;
      txt.name=t.data.liveData.adminchatname;
      txt.img=t.data.liveData.adminchatimg;
      txt.txt=txt.data.text;

      txt.type == 4 && t.data.goodsList.forEach((item,idx)=>{
        item.id == txt.data.goodsId && (txt.idx = idx);
      });
    }
    txtMsgList.push(txt);
    t.setData({txtMsgList},function () {
      t.data.tabActive || (t.data.keyHeight || wx.pageScrollTo({selector:'#footer'}))
    })
  },
  reply(e){ //回复消息
    let t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes) return;
    //console.log(item.name+': '+item.txt);
    t.setInput({},item.name,item.name+': '+item.txt);
  },
  // 禁言
  setNoMsg(e){
    var t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes || item.admin) return;
    //console.log('长按禁言',e);
    d.noMsg.push({
      text:'禁言: '+item.name,
      value:item.token
    });
    t.setData({noMsg:d.noMsg})
  },
  getNoMsg(e){
    let d = this.data;
    this.setData({noMsg:[]})
    if(e.type == 'actiontap'){
      app.args.request({
        url: d._api_live + 'live/forbidSendMsg',
        data:{
          hosId: app.args.api.siteinfo.hosId2,
          userID: e.detail.value,
          liveId: d.options.id
        },
        success(){wx.showToast({title:'禁言成功',icon:'none'})}
      })
    }
  },

  //商品列表
  getGoodsList(){
    let t = this,d=t.data;
    app.args.request({
      url: d._api_live + 'live/getGoodsList',
      data:{
        hosId:app.args.api.siteinfo.hosId2,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({goodsList:e.data})
      }
    })
  },
  //卡券列表
  getCradList(){
    let t = this,d=t.data;
    app.args.request({
      url: d._api_live + 'live/couponBatchList',
      data:{
        storeId:app.args.api.siteinfo.acid,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({cradList:e.data})
      }
    })
  },
  //达人帮列表
  getShareList(){
    let t = this,d=t.data;
    app.args.request({
      url: d._api_live + 'live/shareInfoList',
      data:{
        hosId:app.args.api.siteinfo.hosId2,
        liveId:d.options.id,
        page:1,
        items:20,
      },
      success(e){
        e.shareList.length && t.setData({shareList:e.shareList})
      }
    })
  },

  // 礼物
  setShowGigt(){
    var t = this, d = t.data, customerId=wx.getStorageSync('customerId');
    if(d.giftList.length){
      t.setData({
        showGift:true, giftItem:d.giftList[0]
      });
      return;
    }
    //console.log(customerId)
    if(customerId){
      wx.request({
        url:'https://arsmonj.oicp.io/beauty/beautyLive/getGiftListByCustomer',
        data:{
          hosId:app.args.api.siteinfo.hosId2,
          customerId:customerId
        },
        success(e){
          //console.log('请求数据',e)
          e.data.result == 0 && t.setData({
            giftList:e.data.giftList,
            showGift:true,
            giftPoints:e.data.customerPoints,
            giftItem:e.data.giftList[0]
          })
        }
      })
    }else {//access_token 08gmcwWlTT9PtCilS_5ApgLPYgJIexG7
      t.setData({customerId:true})
    }

  },
  setGiftItem(e){
    var item = e.currentTarget.dataset.item;
    this.setData({
      giftItem:item,
      showCount:false,
      giftCount:item.type?1:this.data.giftCount
    })
  },
  giftSubmit(){
    var t = this, d = t.data, customerId=wx.getStorageSync('customerId');
    this.setData({giftSubmitStyle:''})
    wx.request({
      url:'https://arsmonj.oicp.io/beauty/beautyLive/giveGift',
      data:{
        hosId:app.args.api.siteinfo.hosId2,
        customerId:customerId,
        giftId:d.giftItem.id,
        count:d.giftCount,
        roomId:d.liveData.im_group_id,
        liveId:d.liveData.live_id
      },
      success(e){
        e.data.result ?
          wx.showToast({title:e.data.message,icon:'none'}) :
          t.sendGiftIM(t,d);
        t.setData({giftPoints:e.data.data.customerPoints})
      }
    })
    // t.sendGiftIM(t,d);
  },
  sendGiftIM(t,d){
    var item = {
      name:d.userInfo.nickName,
      img:d.userInfo.avatarUrl,
      gift:d.giftItem,
      count:d.giftCount
    }
    var message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushGift',
        description: '礼物',
        extension: JSON.stringify(item)
      }
    });
    liveIM.tim.sendMessage(message);
    t.setGiftTip(item);
  },
  setGiftTip(item){
    var t= this, d = t.data;
    d.giftTipList.push(item);
    t.setData({giftTipList:d.giftTipList});
    item.gift.type && (d.giftTipList1.push(item),d.parserEnd && t.setGiftTip2());
  },
  setGiftTip2(){
    var t= this, d = t.data, l = d.giftTipList1;
    var parser = new SVGA.Parser(), player = new SVGA.Player("#myCanvas");
    d.parserEnd = false;
    l.length ? parser.load(l[0].gift.wx_svgaUrl, function (videoItem) {
      player.setVideoItem(videoItem);
      player.loops=1;
      player.startAnimation();
      player.onFinished(function () {
        l.shift()
        t.setGiftTip2()
      })
    }) : (d.parserEnd=true);
  },
  setShowCount(){
    var d = this.data;
    d.giftItem.type || this.setData({showCount:!d.showCount})
  },
  setGiftSubmitStyle(){
    this.setData({giftSubmitStyle:'gift-submit2'});
  },
  delGift(){this.setData({showGift:false})},
  delShowCount(e){this.setData({giftCount:e.currentTarget.dataset.item, showCount:false})},

  // 红包
  setHB(obj){
    this.setData({HB:{id:obj.hb_batch_id, time:obj.time, show:true}})
  },
  getHB(c){
    //console.log(c.detail)
    this.setData({'HB.show':false})
    let d = this.data,hb = d.HB;
    if(!c.detail) return;
    // 验证手机号码 LCL
    app._get('user/detail', {}, (result) => {
      if (result.data.userInfo.phone == '') {
        wx.navigateTo({
          url: '/pages/phone/index',
        })
      } else {
        wx.navigateTo({
          url:'/cheng/pages/money/money?id='+hb.id+'&count='+c.detail+'&liveId='+d.options.id
        })
      }
    });
  },
  // 点赞
  setZanCount(){
    let t = this;
    t.setData({
      showZan:true,
      zanStart: this.data.zanStart + 1,
      zanCount: this.data.zanCount + 1
    });


    if(timer2) clearTimeout(timer2);
    timer2 = setTimeout(function () {
      t.setData({showZan:false})
    },4000)


    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushZan',
        description: '点赞+1',
        extension: '1'
      }
    });
    liveIM.tim.sendMessage(message);
  },
  
  //输入框
  inputSubmit(){
    let t=this, d=t.data;
    if(!d.txtMsg) return;
    let l=d.txtMsgList;
    var txt = t.setPushTxtMsg(d.txtMsg);
    l.push(txt)
    this.setData({txtMsgList:l, txtMsg:'',replyTxt:'',replyName:''})
    //发送后切换到聊天窗口
    wx.pageScrollTo({selector:'#footer'});
  },
  setInput(e,replyName,replyTxt) {
    //console.log(replyTxt);
    this.setData({showInput: true,txtMsg:'',replyTxt:replyTxt,replyName:'回复：'+replyName})
  },
  delInput(){
    this.setData({showInput: false, keyHeight:0})
  },
  inputText(e){this.setData({txtMsg:e.detail.value})},
  setHeight(e){
    this.setData({
      keyHeight:e.detail.height || 0
    },function () {
      e.detail.height || this.setData({txtMsg:''})
    })
  },


  // 发送聊天消息
  setPushTxtMsg(txt){
    let d = this.data,kefu=d.kefu;
    let txtMsg = {img:kefu.img, name:kefu.name, token:d.token, txt:txt, yes:kefu.yes,replyTxt:d.replyTxt};

    let message = liveIM.tim.createTextMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {text:JSON.stringify(txtMsg)}
    })
    liveIM.tim.sendMessage(message);
    wx.pageScrollTo({selector:'#footer'});
    //console.log(txtMsg)
    return txtMsg;
  },
  // 商品推送
  setGoodsTip(id,t){
    if(timer) clearTimeout(timer);
    //console.log(id)
    t.data.goodsList.forEach((item,idx)=>{
      item.id == id && t.setData({
        showGoodsTip:true,
        tipIdx:idx,
        showContrastTip:false,
        showCradTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showGoodsTip:false})
        },600*1000)
      })
    })
  },
  //发送购买提示
  goGoods(ele){
    let d = this.data;
    let item = ele.currentTarget.dataset.item;
    if(item && item.want_type == 1) {this.want(item);return}
    let user = {
      name:d.userInfo.nickName.substring(0,2)+'**',
      img:d.userInfo.avatarUrl,
    }
    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushMoney',
        description: '正在购买',
        extension: JSON.stringify(user)
      }
    });
    liveIM.tim.sendMessage(message);
    wx.navigateTo({url:ele.currentTarget.dataset.url})
  },

  //想要
  want(item){
    let t = this,d=t.data;
    wx.request({
      url: d._api_live + 'live/wantgood',
      data:{
        storeId:app.args.api.siteinfo.acid,
        liveId:d.options.id,
        access_token:d.token,
        good_id:item.id
      }
    })

  },
  setWant(obj){
    let t = this,d=t.data;
    let idx = d.goodsList.findIndex(i=>i.id==obj.goodsId);
    d.goodsList[idx].want_price = obj.want_price;
    d.goodsList[idx].want_count = obj.want_count;
    d.goodsList[idx].want_type = obj.want_type;
    this.setData({goodsList:d.goodsList})
  },
  // 对比图推送
  setContrastTip(t,d){
    var data = JSON.parse(d)
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == data.goodsId && t.setData({
        showContrastTip:true,
        //showContrast:true,
        contrastTip:data,
        tipIdx:idx,
        showGoodsTip:false,
        showCradTip:false,
        showGift:false
      },function () {
        timer = setTimeout(function () {
          t.setData({showContrastTip:false})
        },60*1000)
      })
    })
  },
  // 对比图+商品弹窗
  setContrast(){this.setData({showContrast:true})},
  delContrast(){this.setData({showContrast:false})},
  //优惠券推送
  setCradTip(t,id){
    if(timer) clearTimeout(timer);
    t.data.cradList.forEach((item,idx)=>{
      item.coupon_batch_id == id && t.setData({
        showCradTip:true,
        tipIdx:idx,
        showGoodsTip:false,
        showContrastTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showCradTip:false})
        },60*1000)
      })
    })
  },

  setGoodsCountTip(obj){
    let o = JSON.parse(obj);
    if(o.count - 0 > 10) return;
    let l = this.data.goodsCountTipList;
    let item = this.data.goodsList.find(i=>i.id == o.goodsId);
    item.count = o.count;l.push(item);
    this.setData({goodsCountTipList:l});
  },
  //购买提示
  setMoneyTip(obj){
    let o = JSON.parse(obj);
    let l = this.data.goodsMoneyTipList;
    l.push(o)
    this.setData({goodsMoneyTipList:l})
  },
  //领取卡券
  getCard(e){
    let idx = e.currentTarget.dataset.idx,
      toast = e.currentTarget.dataset.toast,
      t = this, d = t.data, card = d.cradList[idx];
    //console.log(idx,card)
    if(card.is_over || card.status) return;
    let appUserInfo=wx.getStorageSync('appUserInfo');
    if(appUserInfo){
      wx.request({
        url: d._api_live + 'live/grantCouponId',
        data:{
          storeId:app.args.api.siteinfo.acid,
          liveId:d.options.id,
          couponBatchId:card.coupon_batch_id,
          mobile:appUserInfo.phone,
          access_token:d.token
        },
        success(e){
          var tip = e.data.is_over?'已领完':(e.data.status?'领取成功':'领取失败')
          wx.showToast({title:tip,icon:'none'})
          e.data.coupon_name = e.data.couponBatchName;
          e.data.coupon_batch_id = e.data.couponBatchId;
          d.cradList[idx] = e.data
          t.setData({cradList:d.cradList})
        }
      })
    }else {
      t.setData({customerId:true})
    }
  },


  // 导航栏
  setTabActive(e){
    var idx = e.currentTarget.dataset.idx;
    this.setData({tabActive:idx});
    idx ? wx.pageScrollTo({scrollTop:0,duration:0}) : wx.pageScrollTo({selector:'#footer'});
    idx == 2 && this.getGoodsList();
    idx == 3 && this.getCradList();
    //idx == 4 && this.getShareList();
  },
  //跳转我的优惠券
  setlookcoupon(){
    wx.navigateTo({
      url: '/pages/user/coupon/list/index?currentTab=1',
    })
  },
  // wxParse
  setWxParse(html){
    var that = this;
    WxParse.wxParse('html', 'html', html, that);
  },


  // 返回按钮
  navigateBack(){
    wx.navigateBack({
      delta: 1,
      success(){
        //console.log('success')
      },
      fail(){
        wx.redirectTo({
          url: '/cheng/pages/live-list/live-list'
        })
      }
    })
  },
  //订阅
  setSubscribe(){
    var t = this,d = t.data;
    if(d.liveData.live_status != 3 || d.subscribe) return;
    wx.requestSubscribeMessage({
      tmplIds:d.tplID,
      success(e){
        JSON.stringify(e).indexOf('accept')>0 && t.pushSubscribe()
      }
    })
  },
  pushSubscribe(){
    var t = this,d = t.data;
    app.args.request({
      url: d._api_live + 'live/subscribeLive',
      data:{
        hosId:app.args.api.siteinfo.hosId2,
        userId:d.token,
        liveId:d.liveData.live_id
      },
      success(e){
        wx.showToast({title:'订阅成功',icon:'none'})
        t.setData({subscribe:1})
      }
    })
  },


  // 所有抽奖信息
  setLotteryList(lotteryData){
    var t = this,d=t.data,item=null,list=null;
    list = lotteryData.filter((m,i)=>{
      if(m.lotteryStatus==1) item=m;
      return m.lotteryStatus>0;
    });
    if(list.length<1) return;
    item || (item = list[list.length-1])
    //item.recordList.forEach(i=>{i.nickName = i.nickName.substring(0,2)+'**'})
    item.recordList.forEach(i=>{i.nickName = i.nickName})
    this.setData({
      lotteryItem:item,
      lotteryStatus:item.lotteryStatus,
      lotteryList:list
    })
  },
  startLottery(ext){
    var t = this,d = t.data;
    var ex = JSON.parse(ext),idx = -1;

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }
    // 开始抽奖
    t.setData({
      lotteryStatus:1,
      lotteryItem:ex,
      lotteryList:d.lotteryList,
      uuidYes:'',
      uuidCoupon:''
    })
  },
  endLotter(ext){
    var t = this,d = t.data;
    // 中奖
    var ex = JSON.parse(ext),idx = -1;
    var lotteryItem,uuidYes='',uuidCoupon='';

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }

    ex.recordList.forEach(item=>{
      //item.nickName = item.nickName.substring(0,2)+'**'
      item.nickName = item.nickName
      if(item.token == d.token){
        uuidYes = item.uuId
        uuidCoupon = item.coupon_name
      }
    })
    t.setData({
      lotteryList:d.lotteryList,
      lotteryItem:ex,
      uuidYes,
      uuidCoupon,
      lotteryStatus:2,
      showLotteryHistory:false,
      showGift:false,
      showLottery:true
    })
  },
  // 中奖记录
  setLotteryHistory(){
    var t = this,d = t.data;
    var lotteryHistory = [];
    d.lotteryList.forEach(item=>{
      item.recordList.forEach(l=>{
        l.lotteryName = item.lotteryName
        lotteryHistory.push(l)
      })
    })
    t.setData({
      lotteryHistory,
      showLotteryHistory:true
    })
  },
  setShowLottery(){
    this.setData({
      showLottery:true
    })
  },
  delLottery(){
    this.setData({
      showLottery:false,
      showLotteryHistory:false
    })
  },
  // 点击自动发送评论参与抽奖
  msgLottery(){
    let t = this,d = t.data;
    // lotteryType 1:评论，2：购买
    if(d.lotteryItem.lotteryType == '1'){
      let l=d.txtMsgList;
      let txt = t.setPushTxtMsg(d.lotteryItem.lottery_content);
      l.push(txt)
      this.setData({
        tabActive:0,
        txtMsgList:l,
        txtMsg:'',
        replyTxt:'',
        replyName:'',
        showLottery:false,
        showLotteryHistory:false
      },function () {
        d.txtMsgStop = true
        setTimeout(function () {
          d.txtMsgStop = false
        },500)
      })
      //发送后切换到聊天窗口
      wx.pageScrollTo({selector:'#footer'});
      wx.showToast({icon:'none',title:'参与成功'})
    }else{
      this.setData({
        tabActive:2,
        showLottery:false,
        showLotteryHistory:false
      })
    }
  },
  setCopy(e){
    //console.log(e)
    wx.setClipboardData({
      data:e.currentTarget.dataset.uuid
    })
  },

  // 投诉弹窗
  setModal(){
    this.setData({
      showModal:true
    })
  },
  delModal(){
    this.setData({
      showModal:false
    })
  },

  // 图片放大
  maxImage(e){
    //console.log(e)
    var src = e.currentTarget.dataset.src;
    wx.previewImage({urls:[src]})
  },

  // 设置全屏
  setFullScreen(){
    var t=this,d=t.data;
    t.setData({
      smallWindow:[]
    },function () {
      wx.navigateTo({
        url:'/cheng/pages/live4/live4?url='+d.liveData.pull_url
      })
    })
  //   url:'/cheng/pages/live3/live3?id='+d.options.id
  },

  // 问答
  setQATime(obj){
    this.setData({
      showQA:obj.reward,
      listQA:obj.data.map(i=>{
        i.select = [{v:i.answer_1,bg:''},{v:i.answer_2,bg:''},{v:i.answer_3,bg:''},{v:i.answer_4,bg:''}];
        return i
      }),
      rewardQA:false,
      getQA:false,
      indexQA:0,
      timeQA:10,
      timeOutQA:null,
    },this.startQA)
  },

  startQA(){
    let t = this,d=t.data;
    d.timeOutQA = setInterval(()=>{
      if(d.timeQA>0){
        t.setData({timeQA:--d.timeQA})
      }else if(d.listQA.length-1>d.indexQA && d.listQA[d.indexQA].select.some(i=>i.bg)){
        t.setData({timeQA:10,indexQA:++d.indexQA})
      }else {
        t.setData({timeQA:10, indexQA:0, rewardQA:true})
      }
      d.rewardQA && clearInterval(d.timeOutQA);
    },1000)
  },

  setABCD(e){
    let t = this,d=t.data;
    let idx = e.currentTarget.dataset.idx;
    let item = d.listQA[d.indexQA];
    let index = item.correct_answer-1;

    clearTimeout(d.timeOutQA);
    if(idx == index ){ //选对了
      item.select[idx].bg = '#57E46B';
      app.args.request({
        url: d._api_live + 'live/setqa',
        data:{
          group_id:item.group_id,question_id:item.question_id,
          answer:item.correct_answer,liveId:d.liveData.live_id,
          storeId:app.args.api.siteinfo.acid
        }})
    }else {
      item.select[idx].bg = '#F45742';
      item.select[index].bg = '#57E46B';
    }
    t.setData({listQA:d.listQA})
    setTimeout(()=>{
      d.listQA.length-1>d.indexQA && idx == index?
          t.setData({timeQA:10, indexQA:++d.indexQA},t.startQA) :
          t.setData({timeQA:10, indexQA:0, rewardQA:true,getQA:idx == index });
    },1500)
  },

  hideQA(){
    this.setData({showQA:'',listQA:[],indexQA:0, timeQA:10,rewardQA:false,getQA:false})
  },


  catchtap(){},

  /*
  * 直播密码模式：验证密码
  */
inputPwds(e){this.setData({txtPwds:e.detail.value})},
 typesPswSubmit(e){
  //console.log(e)
  let t=this, d=t.data;
  if (d.txtPwds == '') {
    wx.showToast({icon:'none',title:'请输入邀请码'})
    return
  }
  app.args.request({
    url: d._api_live + 'live/checkInvitePwd',
    data:{
      hosId: app.args.api.siteinfo.hosId2,
      openId:d.token,
      liveId:d.options.id,
      invitePwd:d.txtPwds
    },
    success(res){
      if(res.resultcode == 1){
        t.init(t,d.options,d.token);
      }else{
        wx.hideLoading()
        wx.showToast({icon:'none',title:'邀请码错误'})
      }
    }
  })
},

/**
 * 付费直播
 */
onSubmitOrder() {
  // 显示loading
  wx.showLoading({
    title: '正在处理...'
  });
  let _this = this,
    options = _this.data.options;
  if (_this.data.disabled) {
    return false;
  }
  // 表单验证
  if (!_this._onVerify()) {
    return false;
  }
  if (_this.data.phone == '') {
    wx.navigateTo({
      url: '/pages/phone/index',
    })
    wx.hideLoading();
    return false;
  } 
  // 按钮禁用, 防止二次提交
  _this.setData({
    disabled: true
  });
  let url = 'order/buyNow';

  // 表单提交的数据
  let postData = {
    delivery: 20,   //20=上门自提
    pay_type: 20,   //20=微信支付
    linkman: _this.data.linkman,  //自提联系人
    phone: _this.data.phone,  //自提联系人手机
    coupon_id: 0,  //是否使用优惠券，默认0
    is_use_points: 0,  //是否积分抵扣，默认0
    remark: '直播间付费',
    referee_id: wx.getStorageSync('referee_id'),  //购买推荐人
    source: wx.getStorageSync('source'),  //购买来源
    goods_id: _this.data.live_goods_id,  //商品ID
    goods_num: 1,  //商品数量
    goods_sku_id: 0,  //商品sku属性
  };


    // 订单提交
    app._post_form(url, postData, result => {
      _this._onSubmitCallback(result);
    }, result => { }, () => {
      wx.hideLoading();
      // 解除按钮禁用
      _this.setData({
        disabled: false
      });
    });
    // 不允许刷新
    _this.setData({
      notRefresh: true
    });

},

/**
 * 表单验证
 */
_onVerify() {
  let _this = this;
  if (_this.data.has_error) {
    app.showError(_this.data.error_msg);
    return false;
  }
  return true;
},

/**
 * 订单提交成功后回调
 */
_onSubmitCallback(result) {
  let _this = this, d=_this.data;
  // 订单创建成功后回调--微信支付
  if (result.code === -10) {
    app.showError(result.msg, () => {
      _this.redirectToOrderIndex(_this,d.parmas,d.token);
    });
    return false;
  }
  // 发起微信支付
  if (result.data.pay_type == 20) {
    app.wxPayment({
      payment: result.data.payment,
      success: res => {
        _this.redirectToOrderIndex(_this,d.parmas,d.token);
      },
      fail: res => {
        app.showError(result.msg.error, () => {
          _this.redirectToOrderIndex(_this,d.parmas,d.token);
        });
      },
    });
  }
},

/**
 * 付款成功后进行直播数据加载
 */
redirectToOrderIndex(t,e,token) {
  t.init(t,e,token);
},

/**
 * 获取用户信息
 */
  getUserInfo() {
    let _this = this;
    app._get('user/detail', {}, (result) => {
      // 判断手机号非空
      if (result.data.userInfo.phone != '') {
        _this.setData({
          linkman: result.data.userInfo.phone,
          phone: result.data.userInfo.phone,
        });
      }else{
        wx.navigateTo({
          url: '/pages/phone/index',
        })
      } 
    });
  },


  // 签到
  setCheckin(){
    let t=this, d=t.data;
    app._get('user/detail', {}, (result) => {
      //console.log(result.data)
      if (result.data.userInfo.phone == '') {
        wx.navigateTo({
          url: '/pages/phone/index',
        })
      } else {
        wx.showLoading()
        wx.request({
            url: d._api_live + "live/signuser",
            data:{
              hosId:app.args.api.siteinfo.hosId2,
              liveId:d.options.id,
              openId:wx.getStorageSync('ACCESS_TOKEN')
            },
            success(e){
              e = e.data;
              //console.log(e)
              wx.hideLoading()
              wx.showToast({icon:'none',title:e.msg})
              if(d.signup_mode == 1){
                t.setData({sign_status:1})
              }
              if(d.signup_mode == 2){
                t.setSign(0);
              }
            }
          })
      }
    });
  },

  // 弹出奖励模式的签到信息
  setSign(types = 1){
    let t=this, d=t.data;
    app._get('user/detail', {}, (result) => {
      if (result.data.userInfo.phone == '') {
        wx.navigateTo({
          url: '/pages/phone/index',
        })
      } else {
        types && wx.showLoading()
        wx.request({
            url: d._api_live + "live/signCheck",
            data:{
              hosId:app.args.api.siteinfo.hosId2,
              liveId:d.options.id,
              openId:wx.getStorageSync('ACCESS_TOKEN')
            },
            success(e){
              e = e.data;
              //console.log(e)
              types && wx.hideLoading()
              let sharelist = [];
              for (var i = 0; i < e.type2maxnum; i++)
              {
                if(e.shareData){
                  sharelist[i] = i < e.shareData.length ? e.shareData[i].shareAvatarUrl : '';
                }else{
                  sharelist[i] = '';
                }
              }
              if(e.sign_rule.length > 0){
                e.sign_rule = e.sign_rule.replace(/\\t/g,'\n')
              }
              t.setData({
                signData:e,
                shareData:sharelist,
                showCheckin:true,
              })
            }
          })
      }
    });
  },
  delSign(){
    this.setData({
      showCheckin:false,
    })
  },

  // 进入我的优惠券
  checkin_mylink(){
    wx.navigateTo({
      url: '/pages/user/coupon/list/index?currentTab=1',
    })
  },

  // 领取好友签到奖励
  friendCheckin(){
    let t=this, d=t.data;
    app._get('user/detail', {}, (result) => {
      //console.log(result.data)
      if (result.data.userInfo.phone == '') {
        wx.navigateTo({
          url: '/pages/phone/index',
        })
      } else {
        wx.showLoading()
        wx.request({
            url: d._api_live + "live/signReward",
            data:{
              hosId:app.args.api.siteinfo.hosId2,
              liveId:d.options.id,
              openId:wx.getStorageSync('ACCESS_TOKEN')
            },
            success(e){
              e = e.data;
              //console.log(e)
              wx.hideLoading()
              wx.showToast({icon:'none',title:e.message})
              t.setSign(0);
            }
          })
      }
    });
  },

  //签到规则说明
  checkin_rule(){
    this.setData({
      showRule:true,
    })
  },
  delRule(){
    this.setData({
      showRule:false,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    // 获取到用户信息
    if(wx.getStorageSync('ACCESS_TOKEN')){
      _this.getUserInfo();
    }
    this.setData({
      smallWindow:['push']
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    liveIM.tim && liveIM.kill();
  },
  //左右滑动提示
  checkinleright(){
    wx.showToast({title:'按住好友列表可左右滑动',icon:'none'})
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var d = this.data,l= d.liveData;
    return {
      title:l.room_name,
      path:'/cheng/pages/live2/live2?id='+d.parmas.id+'&oriToken='+d.token+'&referee_id='+wx.getStorageSync('user_id'),
      imageUrl:l.share_img
    }
  }
})